%%% Copyright [heng] [litaocheng@gmail.com] 
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License. 
%%% You may obtain a copy of the License at 
%%%    http://www.apache.org/licenses/LICENSE-2.0 
%%% Unless required by applicable law or agreed to in writing, 
%%% software distributed under the License is distributed on an "AS IS" BASIS, 
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
%%% See the License for the specific language governing permissions and 
%%% limitations under the License. 

%%% @doc heng worker app and supervisor callback module
-module(heng_worker).
-author('litaocheng@gmail.com').
-vsn('0.1').
-include("heng_worker.hrl").

-behaviour(application).
-behaviour(supervisor).

-export([start/2, stop/1]).
-export([init/1]).

%% @doc start the application from the erl shell
-spec start() ->
    'ok' | {'error', atom()}.
start() ->
    application:start(heng_worker).

%% @doc the application start callback
start(_Type, _Args) ->
    ?Debug("start application~n", []),    
    ensure_apps(),
    
    ?Debug("start the supervisor heng_worker_sup ~n", []),
    supervisor:start_link({local, heng_worker_sup}, ?MODULE, []).
    

%% @doc the application  stop callback
stop(_State) ->
    ok.

%% @doc supervisor callback
init(_Args) -> 
    ?Debug("init supervisor~n", []),
    
    Stragegy = {one_for_one, 10, 10},
    
    %% get the arguments
    Args = {Master, Report, SessKey} = get_args(),    

    ModReport = {heng_worker_reporter, {heng_worker_reporter, start_link, [Args]},
                permanent, 1000, worker, [heng_worker_reporter]},
    
    {ok, {Stragegy, [
                    ModReport
                    ]}
    }.

%%
%% internal API
%%

%% first ensure some apps must start
ensure_apps() ->
    application:start(sasl),
    application:start(os_mon),
    inets:start(),
    crypto:start(),
    ok.

%% get the args
get_args() ->
    {ok, [[Master]]} = init:get_argument(master),
    {ok, [[Report]]} = init:get_argument(report),
    {ok, [[Key]]} = init:get_argument(sesskey),
    {Master, Report, Key}.

